<?php
/********************************************************
** Copyright 2010-2013. Todos los derechos reservados. **
** Desarrollado y Gestionado por:					   **
** Sugey Quintero (Analista)						   **
** José G. De Freitas (Programador)					   **
** Klaudia Uribe (Diseñadora Web)					   **
** Cesar Isturiz (Diseñador Web)					   **
**				S E A  v1.0							   **
*********************************************************/

session_start();
include("conexion.php");

	if (isset($_SESSION['name']) and isset($_SESSION['tiempo'])) {
        if (time()-$_SESSION['tiempo'] > 900) {
			echo "<script>alert('Lo siento, ha estado mas de 15 minutos inactivo. Vuelva a ingresar al sistema');</script>";
			echo "<script>document.location.href='salir.php';</script>";
        } else{
			$_SESSION['tiempo'] = time();
		}
	date_default_timezone_set('America/Caracas'); setlocale(LC_TIME, 'spanish');
	$usuario = $_SESSION['name'];
	$fecha = date("Y-m-d H:i:s");
	$auditoria = mysql_query("INSERT INTO auditoria SELECT '$usuario', '$fecha' , 'Backup Base de Datos Liceo' ");

    }else {
		echo "<script>alert('Debe ingresar al sistema primero');</script>";
		echo "<script>document.location.href='index.php';</script>";
	}

$db_server		= "127.0.0.1"; 
$db_name		= "mydb"; 
$db_username	= "root"; 
$db_password	= "20067522"; 

//  Nombre del archivo.
date_default_timezone_set('America/Caracas'); setlocale(LC_TIME, 'spanish');
$filename 	= "BackupDB_Liceo_".date("d_m_Y_H_i").".sql";


//------------------------------------------------------------------------------------------
//  No tocar
	error_reporting( E_ALL & ~E_NOTICE );
	define( 'Str_VERS', "1.1.1" );
	define( 'Str_DATE', "18 de Marzo de 2005" );
//------------------------------------------------------------------------------------------
//  Funciones

	error_reporting( E_ALL & ~E_NOTICE );

	function fetch_table_dump_sql($table, $fp = 0) {
		$tabledump = "--\n";
		if( !$hay_Zlib ) 
			fwrite($fp, $tabledump);
		else
			gzwrite($fp, $tabledump);	
		$tabledump = "-- Table structure for table `$table`\n";
		if( !$hay_Zlib ) 
			fwrite($fp, $tabledump);
		else
			gzwrite($fp, $tabledump);	
		$tabledump = "--\n\n";
		if( !$hay_Zlib ) 
			fwrite($fp, $tabledump);
		else
			gzwrite($fp, $tabledump);	

		$tabledump = query_first("SHOW CREATE TABLE $table");
		strip_backticks($tabledump['Create Table']);
		$tabledump = "DROP TABLE IF EXISTS $table;\n" . $tabledump['Create Table'] . ";\n\n";
		if( !$hay_Zlib ) 
			fwrite($fp, $tabledump);
		else
			gzwrite($fp, $tabledump);	

		$tabledump = "--\n";
		if( !$hay_Zlib ) 
			fwrite($fp, $tabledump);
		else
			gzwrite($fp, $tabledump);	
		$tabledump = "-- Dumping data for table `$table`\n";
		if( !$hay_Zlib ) 
			fwrite($fp, $tabledump);
		else
			gzwrite($fp, $tabledump);	
		$tabledump = "--\n\n";
		if( !$hay_Zlib ) 
			fwrite($fp, $tabledump);
		else
			gzwrite($fp, $tabledump);	

		$tabledump = "LOCK TABLES $table WRITE;\n";
		if( !$hay_Zlib ) 
			fwrite($fp, $tabledump);
		else
			gzwrite($fp, $tabledump);	

		$rows = query("SELECT * FROM $table");
		$numfields=mysql_num_fields($rows);
		while ($row = fetch_array($rows, DBARRAY_NUM)) {
			$tabledump = "INSERT INTO $table VALUES(";
			$fieldcounter = -1;
			$firstfield = 1;
			// campos
			while (++$fieldcounter < $numfields) {
				if( !$firstfield) {
					$tabledump .= ', ';
				}
				else {
					$firstfield = 0;
				}
				if( !isset($row["$fieldcounter"])) {
					$tabledump .= 'NULL';
				}
				else {
					$tabledump .= "'" . mysql_escape_string($row["$fieldcounter"]) . "'";
				}
			}
			$tabledump .= ");\n";
			if( !$hay_Zlib ) 
				fwrite($fp, $tabledump);
			else
				gzwrite($fp, $tabledump);	
		}
		free_result($rows);
		$tabledump = "UNLOCK TABLES;\n";
		if( !$hay_Zlib ) 
			fwrite($fp, $tabledump);
		else
			gzwrite($fp, $tabledump);	
	}

	function strip_backticks(&$text) {
		return $text;
	}

	function fetch_array($query_id=-1) {
		if( $query_id!=-1) {
			$query_id=$query_id;
		}
		$record = mysql_fetch_array($query_id);
		return $record;
	}

	function problemas($msg) {
		$errdesc = mysql_error();
    $errno = mysql_errno();
    $message  = "<br>";
    $message .= "- Ha habido un problema accediendo a la Base de Datos<br>";
    $message .= "- Error $appname: $msg<br>";
    $message .= "- Error mysql: $errdesc<br>";
    $message .= "- Error número mysql: $errno<br>";
    $message .= "- Script: ".getenv("REQUEST_URI")."<br>";
    $message .= "- Referer: ".getenv("HTTP_REFERER")."<br>";
	die("");
  }

	function free_result($query_id=-1) {
    if( $query_id!=-1) {
      $query_id=$query_id;
    }
    return @mysql_free_result($query_id);
  }

  function query_first($query_string) {
    $res = query($query_string);
    $returnarray = fetch_array($res);
    free_result($res);
    return $returnarray;
  }

	function query($query_string) {
    $query_id = mysql_query($query_string);
    if( !$query_id) {
      problemas("Invalid SQL: ".$query_string);
    }
    return $query_id;
  }


//------------------------------------------------------------------------------------------
//  Main
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Respaldo DB</title>
<link rel="shortcut icon" type="image/x-icon" href="../favicon.ico">
<link href="style.css" rel="stylesheet" type="text/css" />
<!-- calendario-->
<link rel="stylesheet" type="text/css" href="src/css/jscal2.css" />
<link rel="stylesheet" type="text/css" href="src/css/border-radius.css" />
<link rel="stylesheet" type="text/css" href="src/css/steel/steel.css" />
<script type="text/javascript" src="src/js/jscal2.js"></script>
<script type="text/javascript" src="src/js/lang/es.js"></script>
<!-- fin calendario-->
<!-- botones-->
<link type="text/css" href="js/css/smoothness/jquery-ui-1.8.16.custom.css" rel="Stylesheet" />      
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script> 
<script>
var j$ = jQuery.noConflict();
j$(document).ready(function(){
j$(".button").button();
});

j$(function(){
	j$('#menu li a').click(function(event){
		var elem = j$(this).next();
		if(elem.is('ul')){
			event.preventDefault();
			j$('#menu ul:visible').not(elem).slideUp();
			elem.slideToggle();
		}
	});
});
</script>
<!-- fin botones-->
</head>

<body>
<div id="wrap">
<div id="header">
<div id="hora">
<?php include("Hora.php"); ?>
</div>
<div id="topnav">
	<?php include("MenuSuperior.php"); ?>
</div>
</div>
<div id="content">
<div id="left">
<div class="post">
<div class="post_h">

</div>

<div class="postcontent">

<blockquote><h2 align="center">RESPALDO BASE DE DATOS</h2></blockquote>
<fieldset>
<legend align=left><b><font size=2>INFORMACION</font></b></legend>
<table width=100% cellspacing=15 cellpadding=5 border=0>	
<?php
	@set_time_limit( 0 );
	$error = false;
	$tablas = 0;

	if( !@function_exists( 'gzopen' ) ) {
		$hay_Zlib = false;
	}
	else {
		$filename = "BackupDB/".$filename . ".gz";
		$hay_Zlib = true;
	}
	
	if( !$error ) { 
	    $dbconnection = @mysql_connect( $db_server, $db_username, $db_password ); 
	    if( $dbconnection) 
	        $db = mysql_select_db( $db_name );
	    if( !$dbconnection || !$db ) { 
	        echo( "<tr><td>La conexion con la Base de datos ha fallado: ".mysql_error()."</td></tr>" );
	        $error = true;
	    }
	    else {
	        echo( "<tr><td>Se ha establecido conexion con la Base de datos.</td></tr>" );
	    }
	}

	if( !$error ) { 
		//  MySQL versión
		$result = mysql_query( 'SELECT VERSION() AS version' );
		if( $result != FALSE && @mysql_num_rows($result) > 0 ) {
			$row   = mysql_fetch_array($result);
		} else {
			$result = @mysql_query( 'SHOW VARIABLES LIKE \'version\'' );
			if( $result != FALSE && @mysql_num_rows($result) > 0 ){
				$row   = mysql_fetch_row( $result );
			}
		}
		if(! isset($row) ) {
			$row['version'] = '3.21.0';
		}
	}

	if( !$error ) { 
		$el_path = getenv("REQUEST_URI");
		$el_path = substr($el_path, strpos($el_path, "/"), strrpos($el_path, "/"));

		$result = mysql_query("SHOW TABLES FROM $db_name");
		if( !$result ) {
			print "<tr><td>Error, no se pudo obtener la lista de las tablas.</td></tr>";
			print '<tr><td>MySQL Error: ' . mysql_error(). '</td></tr>';
			$error = true;
		}
		else {
			$t_start = time();
			
			if( !$hay_Zlib ) 
				$filehandle = fopen( $filename, 'w' );
			else
				$filehandle = gzopen( $filename, 'w6' );	//  nivel de compresión
				
			if( !$filehandle ) {
				$el_path = getenv("REQUEST_URI");
				$el_path = substr($el_path, strpos($el_path, "/"), strrpos($el_path, "/"));
				echo( "<tr><td>No se ha podido crear '$filename' en '$el_path/'. Por favor, asegúrese de que dispone de privilegios de escritura.</td></tr>" );
			}
			else {					
				$tabledump = "-- Backup de la Base de Datos\n";
				if( !$hay_Zlib ) 
					fwrite( $filehandle, $tabledump );
				else
					gzwrite( $filehandle, $tabledump );	
				setlocale( LC_TIME,"spanish" );
				$tabledump = "-- Fecha: " . strftime( "%A %d %B %Y - %H:%M:%S", time() ) . "\n";
				if( !$hay_Zlib ) 
					fwrite( $filehandle, $tabledump );
				else
					gzwrite( $filehandle, $tabledump );	
				$tabledump = "--\n";
				if( !$hay_Zlib ) 
					fwrite( $filehandle, $tabledump );
				else
					gzwrite( $filehandle, $tabledump );	
				$tabledump = "-- Version: " . Str_VERS . ", del " . Str_DATE . "\n";
				if( !$hay_Zlib ) 
					fwrite( $filehandle, $tabledump );
				else
					gzwrite( $filehandle, $tabledump );	
				$tabledump = "--\n";
				if( !$hay_Zlib ) 
					fwrite( $filehandle, $tabledump );
				else
					gzwrite( $filehandle, $tabledump );	
				$tabledump = "-- Host: `$db_server`    Database: `$db_name`\n";
				if( !$hay_Zlib ) 
					fwrite( $filehandle, $tabledump );
				else
					gzwrite( $filehandle, $tabledump );	
				$tabledump = "-- ------------------------------------------------------\n";
				if( !$hay_Zlib ) 
					fwrite( $filehandle, $tabledump );
				else
					gzwrite( $filehandle, $tabledump );	
				$tabledump = "-- Server version	". $row['version'] . "\n\n";
				if( !$hay_Zlib ) 
					fwrite( $filehandle, $tabledump );
				else
					gzwrite( $filehandle, $tabledump );	

				$result = query( 'SHOW tables' );
				while( $currow = fetch_array($result, DBARRAY_NUM) ) {
					fetch_table_dump_sql( $currow[0], $filehandle );
					fwrite( $filehandle, "\n" );
					if( !$hay_Zlib ) 
						fwrite( $filehandle, "\n" );
					else
						gzwrite( $filehandle, "\n" );
						$tablas++;
				}
				$tabledump = "\n-- Backup de la Base de Datos Completo.";
				if( !$hay_Zlib ) 
					fwrite( $filehandle, $tabledump );
				else
					gzwrite( $filehandle, $tabledump );	
				if( !$hay_Zlib ) 
					fclose( $filehandle );
				else
					gzclose( $filehandle );
	
				$t_now = time();
				$t_delta = $t_now - $t_start;
				if( !$t_delta )
					$t_delta = 1;
				$t_delta = floor(($t_delta-(floor($t_delta/3600)*3600))/60)." minutos y "
				.floor($t_delta-(floor($t_delta/60))*60)." segundos.";
				echo( "<tr><td>Se ha salvado las $tablas tablas en $t_delta</td></tr>" );
				echo( "<tr><td>El Backup de la Base de Datos est&aacute; completo.</td></tr>" );
				echo( "<tr><td>Se ha guardado una copia del backup de la Base de Datos en: $el_path/$filename<br>" );
				//echo( "<tr><td>Puede descargarla directamente: <a href=\"$filename\">$filename</a>" );
				$size = filesize($filename);
				$size = number_format( $size );
				$size = str_replace( ",",".",$size );
				echo( "Tama&ntilde;o: ($size bytes)</td></tr>" );
			}
		}
	}

	if( $dbconnection )
	    mysql_close();
	
//------------------------------------------------------------------------------------------
//  END
?>
</table>
</form>
</fieldset>

<div class="post">
<span></span></div>

<div id=botonera align=center>
	<input class=button type=button value=Volver onClick=location='Configurar.php'>
</div>

</div>
<div class="post_b">
<span></span></div>
</div>


</div>

<div class="post">
<div class="post_h">

</div>


</div>

<?php include("Menu.php"); ?>

<div class="clear"></div>
</div>
<div id="pagebottom"></div>

<div id="footer">
<P>&reg; Derechos Reservados @ CopyRight. 2011-2012</P>
<p>Programadores: Quintero E, Isturiz C, Uribe C, De Freitas J.</p>
</div>
</div>
</body>
</html>
<?php echo "<script>document.location.href='$filename';</script>"; ?>
